package cn.piggy.gateway.core.client;

import cn.piggy.gateway.core.common.CommonUtil;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PiggyClientHandler extends ChannelInboundHandlerAdapter {
    private Logger logger = LoggerFactory.getLogger(PiggyClientHandler.class);
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        logger.info("client receive response ---> {}", msg.toString());
        Response response = JSONObject.parseObject(msg.toString(), Response.class);
        Long id = response.getId();
        Request request = CommonUtil.futures.get(id);
        request.receiveResult(response);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        String application = ctx.channel().attr(AttributeKey.valueOf("application")).get().toString();
        String address = ctx.channel().attr(AttributeKey.valueOf("address")).get().toString();
        NettyClient.remove(application,address);
    }

}
